package org.bbs.demo.user.api;

import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.advice.SysException;
import org.bbs.demo.common.Result;
import org.bbs.demo.common.ResultToken;
import org.bbs.demo.user.dao.UserLoginDao;
import org.bbs.demo.user.dto.UserLoginDto;
import org.bbs.demo.utils.TokenUser;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class UserLoginApi {

    @Autowired
    private UserLoginDao userLoginDao;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody UserLoginDto loginDto){

        // 判断登录方式 mail/uid
        if (loginDto.getUserAccount().contains("@")) {

            String userId = null;
            try {
                userId = userLoginDao.getUserIdByMailAndPwd(loginDto);
            }
            catch (Exception e){
                throw new SysException("访问数据库错误", e);
            }
            if (userId != null) {
                ResultToken resultToken = new ResultToken(JWTutil.createToken(new TokenUser(userId, loginDto.getUserAccount())));
                return Result.OK("登录成功", resultToken);
            }

        } else {

            String userMail;
            try {
                userMail = userLoginDao.getUserMailByUidAndPwd(loginDto);
            }
            catch (Exception e){
                throw new SysException("访问数据库错误", e);
            }
            if (userMail != null) {
                ResultToken resultToken = new ResultToken(JWTutil.createToken(new TokenUser(loginDto.getUserAccount(), userMail)));
//                System.out.println(resultToken);
                return Result.OK("登录成功", resultToken);
            }

        }

        throw new BusinessException("账号或密码错误");

    }

    @GetMapping("/curr-user")
    public Result getUser(@RequestHeader String Token){
        TokenUser tokenUser = new TokenUser(JWTutil.getUserID(Token), JWTutil.getMail(Token));
        return Result.OK(tokenUser);
    }

}
